# 加载e1071包
if (!require(e1071)) install.packages("e1071")
library(e1071)
library(caret)
library(pROC)
library(MatchIt)

# 设置工作目录并加载数据
setwd("${path}")
mydata <- read.csv("data.csv")
# 确保 ${hotspot} 是因子，并且值为 "event_0" 和 "event_1"
mydata$${hotspot} <- factor(mydata$${hotspot}, levels = c("0", "1"), labels = c("event_0", "event_1"))


# 使用 matchit 进行 1:3 匹配
m.out <- matchit(${hotspot} ~ ${independent_and}, 
                 data = mydata, 
                 method = "nearest", 
                 ratio = 3)

# 提取匹配后的数据
matched_data <- match.data(m.out)
# 训练SVM模型
model_svm <- svm(
  ${hotspot} ~ ${independent_and},
  data = matched_data,
  kernel = "radial",
  cost = 1,
  gamma = 0.1,
  probability = TRUE
)

# 预测和评估
predictions_svm <- predict(model_svm, newdata = matched_data, probability = TRUE)
predicted_probs_svm <- attr(predictions_svm, "probabilities")[,2]
predicted_classes_svm <- predictions_svm

# 添加预测结果到数据集
mydata_with_predictions_svm <- matched_data %>%
  mutate(
    ${hotspot}_probability = predicted_probs_svm,
    ${hotspot}_predicted_class = predicted_classes_svm,
    ${hotspot}_score = NA  # SVM没有评分卡
  )
# 计算 ${hotspot} 和 ${hotspot}_predicted_class 相同的数据数量
matching_rows <- mydata_with_predictions_svm %>%
  filter(${hotspot} == ${hotspot}_predicted_class) %>%
  nrow()
# 打印结果
cat("Number of rows where ${hotspot} and ${hotspot}_predicted_class match:", matching_rows, "\n")
# 可选：计算准确率（匹配行数 / 总行数）
total_rows <- nrow(matched_data)
accuracy <- matching_rows / total_rows
# 打印结果
cat("Number of rows where ${hotspot} and ${hotspot}_predicted_class match:", accuracy, "\n")
# 这是建模集的结果
write.csv(mydata_with_predictions_svm, file = "mydata_with_predictions_svm.csv", row.names = FALSE)

#### 支持向量图 ####
# 提取支持向量的索引
support_vector_indices <- model_svm$index

# 使用这些索引从原始数据中获取支持向量
support_vectors <- matched_data[support_vector_indices, ]

# 绘制散点图并突出显示支持向量
plot_svm <- ggplot(matched_data, aes(x = auth_sum, y = impact_factor, color = factor(${hotspot}))) +
  geom_point(alpha = 0.6) + # 原始数据点
  geom_point(data = support_vectors, aes(x = auth_sum, y = impact_factor), shape = 4, size = 3, color = "red") + # 支持向量
  labs(title = "Support Vectors Plot", x = "Author Sum", y = "Impact Factor") +
  theme_minimal()

Cairo::CairoTIFF(file="svm_svm.tiff", width=800, height=800,units="in",dpi=150)
print(plot_svm)
dev.off()
#### 混淆矩阵 ####
library(caret)
conf_matrix <- confusionMatrix(factor(predicted_classes_svm), factor(matched_data$${hotspot}))

sink("confusionMatrix_svm.txt")
print(conf_matrix)
sink()

#### ROC曲线 ####

# 绘制ROC曲线

# 绘制ROC曲线
roc_curve <- roc(matched_data$group_sum, predicted_probs_svm)
png(file="roc_svm.tiff", width=800, height=800,units="in",dpi=150)
plot(roc_curve, col = "#e41a1c", lwd = 2, main = "ROC Curve")
legend("bottomright", legend = paste("AUC =", round(auc(roc_curve), 2)), bty = "n")
dev.off()


#### 学习曲线 ####
learning_curve_data <- createDataPartition(mydata$${hotspot}, p = .8, list = FALSE)
train_indices <- learning_curve_data
test_indices <- setdiff(1:nrow(mydata), train_indices)

# 训练并评估模型在不同大小的数据集上的表现
sizes <- seq(0.1, 1, by = 0.1)
accuracy_list <- sapply(sizes, function(size) {
  subset_indices <- sample(train_indices, size * length(train_indices))
  model <- svm(${hotspot} ~ ., data = mydata[subset_indices, ], kernel = "radial", cost = 1, gamma = 0.1, probability = TRUE)
  predictions <- predict(model, newdata = mydata[test_indices, ])
  conf_matrix <- confusionMatrix(predictions, mydata$${hotspot}[test_indices])
  return(conf_matrix$overall['Accuracy'])
})

# 绘制学习曲线
learning_curve_plot <- ggplot(data = data.frame(Size = sizes, Accuracy = accuracy_list), aes(x = Size, y = Accuracy)) +
  geom_line(color = "green", size = 1) +
  geom_point() +
  labs(title = "Learning Curve", x = "Training Set Size Proportion", y = "Accuracy") +
  theme_minimal()
Cairo::CairoTIFF(file="learningCurve_svm.tiff", width=800, height=800,units="in",dpi=150)
print(learning_curve_plot)
dev.off()
mydata1 <- read.csv("result.csv")
# 预测和评估
predictions_svm <- predict(model_svm, newdata = mydata1, probability = TRUE)
predicted_probs_svm <- attr(predictions_svm, "probabilities")[,2]
predicted_classes_svm <- predictions_svm

# 添加预测结果到数据集
result_with_predictions_svm <- mydata1 %>%
  mutate(
    ${hotspot}_probability = predicted_probs_svm,
    ${hotspot}_predicted_class = predicted_classes_svm,
    ${hotspot}_score = NA  # SVM没有评分卡
  )
# 这是结局的结果
write.csv(result_with_predictions_svm, file = "result_with_predictions_svm.csv", row.names = FALSE)
